package cn.snowsoft.iot.module.warning.rabbitmq;

import cn.snowsoft.iot.module.warning.controller.admin.warning.config.vo.WarningDetailVO;
import cn.snowsoft.iot.module.warning.event.MessageWarningEvent;
import cn.snowsoft.iot.module.warning.event.MysqlWarningEvent;
import cn.snowsoft.iot.module.warning.event.WarningEvent;
import cn.snowsoft.iot.module.warning.service.warning.config.IWarningService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.UUID;


@Slf4j
@Component
public class WarningQueueHandler {

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	private IWarningService warningService;

	@Autowired
	private ApplicationEventPublisher eventPublisher;

	@RabbitListener(queues = "iot.warning.result")
	public void warningHandler(JSONObject message) {
		try {
			log.info("warning <===> 接收告警消息：{}", message);
			distributionWarning(message);
		} catch (Exception e) {
            log.error("warning <===> 接收告警消息异常：{}", e);
        }
    }


	private void distributionWarning(JSONObject message) {
		final String uuId = UUID.randomUUID().toString();
		if (message.getJSONObject("last_value") != null) {
			message = message.getJSONObject("last_value");
		}
		Long warningId = message.getLong("warningId");
		WarningDetailVO warningDetailVO = warningService.selectWarningById(warningId);
		JSONObject finalMessage = message;
		warningDetailVO.getActionDOList().forEach(action -> {
			WarningEvent event;
			//根据动作的小类型区分不同事件，0-6 为消息类型，mqtt、http是北向输出，feature是设备反控
			switch (action.getOutputWay()) {
				// 当动作是 站内信、电话、短信、邮件、钉钉、企业微信、飞书
				case "0" :
					event = new MessageWarningEvent(finalMessage, action.getRelatedParameter(), uuId, action.getId(),warningDetailVO);
					break;
				default:
					event = null;
			}
			if (ObjectUtils.isNotEmpty(event)) {
				eventPublisher.publishEvent(event);
				log.info("发布事件完成 {}", event);
			}
		});

		eventPublisher.publishEvent(new MysqlWarningEvent(message, uuId, warningDetailVO.getWarningType()));
	}

	/**
	 * 发送消息到rabbitmq
	 */
	public void sendMessage(String routeKey, String data) {
		rabbitTemplate.convertAndSend("", routeKey, data);
	}
}
